package com.kaluli.project.service;

import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.mail.MessagingException;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kaluli.project.domain.entity.AbroadVO;
import com.kaluli.project.domain.entity.KllMainOrder;
import com.kaluli.project.domain.entity.KllMainOrderDetail;
import com.kaluli.project.domain.entity.KllMq;
import com.kaluli.project.domain.entity.KllOrderLogistics;
import com.kaluli.project.domain.entity.KllOrderSynApi;
import com.kaluli.project.domain.entity.KllWareHouse;
import com.kaluli.project.domain.repository.KllMainOrderDetailRepository;
import com.kaluli.project.domain.repository.KllMainOrderRepository;
import com.kaluli.project.domain.repository.KllOrderLogisticsRepository;
import com.kaluli.project.domain.repository.KllOrderSynApiRepository;
import com.kaluli.project.utils.DateUtil;
import com.kaluli.project.utils.Dom4jUitls;
import com.kaluli.project.utils.HttpUtils;
import com.kaluli.project.utils.MD5Utils;
import com.kaluli.project.utils.RandomNumber;
import com.kaluli.project.utils.nanshaxml.SelXmlBuilder;
import com.kaluli.project.utils.nanshaxml.SelXmlBuilder;

@Service
@Configuration
@Component
@PropertySource({"classpath:thridsystem.properties"})
public class KllOrderSynApiService {

    @Autowired
    private Environment env;

    @Autowired
    private KllMainOrderRepository kllMainOrderRepository;

    @Autowired
    private KllOrderSynApiRepository kllOrderSynApiRepository;

    @Autowired
    private KllMainOrderService kllMainOrderService;

    @Autowired
    private KllMainOrderDetailRepository kllMainOrderDetailRepository;

    @Autowired
    private KllMainOrderDetailService kllMainOrderDetailService;

    @Autowired
    private KllMqService kllMqService;

    @Autowired
    private SendEmailService sendEmailService;

    @Autowired
    private KllOrderLogisticsService kllOrderLogisticsService;

    @Autowired
    private KllOrderLogisticsRepository kllOrderLogisticsRepository;

    @Autowired
    private KllKolOrderService kllKolOrderService;

    @Autowired
    private RestClient client;

    static Logger log = Logger.getLogger(KllOrderSynApiService.class);

    public List<KllOrderSynApi> findSynApiList(String orderNumber) {
        List<KllOrderSynApi> list = new ArrayList<>();

        kllOrderSynApiRepository.findSynApiList(orderNumber);
        return list;

    }

    public Map<String, Object> updateSendNr(String orderNumber) {
        Map<String, Object> map = new HashMap<>();
        try {
            KllOrderSynApi api = kllOrderSynApiRepository.findByOrderNumber(orderNumber);
            if (api == null) {
                map.put("code", 0);
                map.put("message", "获取数据失败!");
            }
            if (api.getSendNr() == 3 || api.getSendNr() == 2 || api.getSendNr() == 4) {
                api.setSendNr(0);
                api.setSendNrDate(new Timestamp(System.currentTimeMillis()));
                kllOrderSynApiRepository.updateSendNr(orderNumber);
                map.put("code", 1);
                map.put("message", "重推成功!");
            } else {
                map.put("code", 0);
                map.put("message", "订单处理中,不能重推!");
            }
        } catch (Exception e) {
            map.put("code", 0);
            map.put("message", "重推失败!");
        }
        return map;

    }

    public Map<String, Object> updateSynApiStatus(String orderNumber) {
        Map<String, Object> map = new HashMap<>();
        try {
            KllOrderSynApi api = kllOrderSynApiRepository.findByOrderNumber(orderNumber);
            if (api == null) {
                map.put("code", 0);
                map.put("message", "获取数据失败!");
            }
            if (api.getSendGj() == 3) {
                api.setSendGj(1);
                api.setSendHg(1);
                api.setSendGjDate(new Timestamp(System.currentTimeMillis()));
                api.setSendHgDate(new Timestamp(System.currentTimeMillis()));
                kllOrderSynApiRepository.updateNSynStart(orderNumber);
            } else {
                api.setSendHg(1);
                api.setSendHgDate(new Timestamp(System.currentTimeMillis()));
                kllOrderSynApiRepository.updateSynStatus(orderNumber, "HG");
            }
        } catch (Exception e) {
            map.put("code", 0);
            map.put("message", "更新失败!");
        }
        map.put("code", 1);
        map.put("message", "更新成功!");
        return map;

    }

    /**
     * EDI订单取消回执处理
     *
     * @param ediOrderno
     * @return
     */
    public Map<String, Object> cancelEDIResult(String ediOrderno) {
        Map<String, Object> map = new HashMap<>();
        try {
            //更新主订单状态
            KllOrderSynApi api = kllOrderSynApiRepository.findByEdiOrderno(ediOrderno);
            if (api != null) {
                String username = env.getProperty("user.name.nb");
                kllMainOrderService.cancelResult(api.getOrderNumber(), username);
            }


        } catch (Exception e) {
            map.put("code", 0);
            map.put("message", "更新失败!");
        }
        map.put("code", 1);
        map.put("message", "更新成功!");
        return map;

    }

    /**
     * 从订单表中获取含有南沙保税商品的订单推送到执行池中，并标记
     *
     * @throws Exception
     */
    @Scheduled(cron = "${synOrder.pool.cron}")
    @Transactional(rollbackOn = {RuntimeException.class, Exception.class})
    public synchronized void synOrderToPool() throws Exception {
        log.info("syn order now");
        List<KllMainOrder> mainOrders = kllMainOrderRepository.getListByNSyn();
        a:
        for (KllMainOrder mainOrder : mainOrders) {
            boolean importFlag = false;
            String flag = "";
            int payType = mainOrder.getPayType();
            Set<KllMainOrderDetail> mainOrderDetails = mainOrder.getKllMainOrderDetails();
            b:
            for (KllMainOrderDetail mainOrderDetail : mainOrderDetails) { // 遍历每个订单中是否含有南沙保税的商品
                // KllWareHouse wareHouse =
                // mainOrderDetail.getKllProductSku().getKllWareHouse();
                if (mainOrderDetail.getDepotType().toString().equalsIgnoreCase(env.getProperty("kll.warehouse.ns"))) { // 处理南沙保税商品
                    importFlag = true;
                    flag = env.getProperty("kll.warehouse.ns");
                    break b;
                }
                if (mainOrderDetail.getDepotType().toString().equalsIgnoreCase(env.getProperty("kll.warehouse.nb"))) { // 处理宁波保税商品
                    flag = env.getProperty("kll.warehouse.nb");
                    break b;
                }
            }
            if (StringUtils.isNotBlank(flag)) {
                nsbsWareHouse(mainOrder, flag);
            }

        }
    }

    public void nsbsWareHouse(KllMainOrder mainOrder, String wareType) {
        KllOrderSynApi orderSynApi = new KllOrderSynApi();
        orderSynApi.setOrderNumber(mainOrder.getOrderNumber());
        orderSynApi.setIbillingNumber(mainOrder.getIbillingNumber());
        int i = 0;
        // 判断是否是南沙仓
        if (wareType.equals(env.getProperty("kll.warehouse.nb"))) {
            i = 2;
            orderSynApi.setSendNr(0);
            orderSynApi.setSendAlipayGj(2);
        } else {
            orderSynApi.setSendNr(2);
            orderSynApi.setSendAlipayGj(0);
        }
        orderSynApi.setWareType(wareType);
        orderSynApi.setSendGj(i);
        orderSynApi.setSendHg(i);
        orderSynApi.setSendZz(i);
        orderSynApi.setPayType(mainOrder.getPayType());
        orderSynApi.setSendAlipay(0);
        orderSynApi.setSendWeixin(0);
        orderSynApi.setZt(1);
        log.info("南沙orderSynApi商品number=" + mainOrder.getOrderNumber());
        kllOrderSynApiRepository.save(orderSynApi);
        kllMainOrderRepository.updateOrderSynApi(mainOrder.getOrderNumber());

        // 初始化物流信息记录
        String fuisionjson = mainOrder.getKllMainOrderAttr().getAddressAttr();
        JSONObject ja = JSON.parseObject(fuisionjson);
        String province = ja.getString("province");
        String city = ja.getString("city");
        KllOrderLogistics logistics = new KllOrderLogistics();
        logistics.setOrderNumber(mainOrder.getOrderNumber());
        logistics.setToCity(province + city);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 物流写入 订单提交成功，等待海关清关
        AbroadVO vo = new AbroadVO();
        vo.setContext("订单提交成功，等待海关清关");
        vo.setTime(sf.format(new Date()));
        vo.setFtime(sf.format(new Date()));
        vo.setAreaCode("000000000000");// 虚拟的数据
        vo.setStatus("在途");
        List<AbroadVO> list = new ArrayList<>();
        list.add(vo);
        String json = JSON.toJSONString(list);
        logistics.setAbroad(json);
        logistics.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        logistics.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        logistics.setDomesticStatus("abort");
        kllOrderLogisticsRepository.save(logistics);

        // 物流写入 开始清关
        kllOrderLogisticsService.updateAbroad("开始清关", mainOrder.getOrderNumber());
    }


    /**
     * 组装EDI需要的xml报文
     *
     * @param order
     * @return String
     */
    private synchronized String assmbleyEDIXml(KllOrderSynApi order) {
        SelXmlBuilder xb = SelXmlBuilder.getInstance();

        xb.addHeader(SelXmlBuilder.METHOD_TYPE, env.getProperty("edi.method.type"));
        xb.addHeader(SelXmlBuilder.BUS_CODE, env.getProperty("edi.bus.code"));
        xb.addHeader(SelXmlBuilder.RULE, "1");// rule=1返回是有orderStatus的
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

        xb.addBody(SelXmlBuilder.ORDERNO, order.getEdiOrderno(), true, "request/body");
        // xb.addBody(SelXmlBuilder.STARTTIME, sf.format(new Date()), true,
        // "request/body");
        // xb.addBody(SelXmlBuilder.ENDTIME, sf.format(new Date()), true,
        // "request/body");// 3105=北仑保税区
        return xb.toString();
    }

    /**
     * 执行池中逐个发送给卓志、国检、海关 状态0 未发送 1 已发送未成功 2已发送已成功 0 和 1的订单需要持续发送，直到状态为 2 才停止
     */
    @Scheduled(cron = "${synOrder.thrid.cron}")
    public synchronized void synOrderToThridParty() {
        TradePool pool = TradePool.getTradeInstance();
        List<KllOrderSynApi> synOrders = kllOrderSynApiRepository.listNotPushOrder();
        for (KllOrderSynApi synOrder : synOrders) {
            String nrType = env.getProperty("kll.warehouse.nb");
            String nsType = env.getProperty("kll.warehouse.ns");

            // 能容
            if (synOrder.getSendNr() == 0) {

                if (synOrder.getSendWeixin() == 2 || synOrder.getSendAlipay() == 2) {

                    TradeQueue tq = pool.getTradeQueue("EDI");
                    if (!tq.isExist(synOrder.getOrderNumber())) {

                        tq.add(synOrder);
                    }
                }
            }

		/*	if (synOrder.getSendGj() == 0 || synOrder.getSendGj() == 1) {

				TradeQueue tq = pool.getTradeQueue("GJ");
				if (!tq.isExist(synOrder.getOrderNumber())) {

					tq.add(synOrder);
				}
			}
			if (synOrder.getSendHg() == 0) {
				TradeQueue tq = pool.getTradeQueue("HG");
				if (!tq.isExist(synOrder.getOrderNumber())) {
					tq.add(synOrder);
				}
				// 物流写入 开始清关
				// kllOrderLogisticsService.updateAbroad("开始清关",
				// synOrder.getOrderNumber());
			}*/

            if ((synOrder.getSendGj() == 2 && synOrder.getSendHg() == 2 && nsType.equals(synOrder.getWareType()))
                    || (synOrder.getSendNr() == 0 && nrType.equals(synOrder.getWareType()))) {

                int payType = synOrder.getPayType();
                if (payType == 2) {
                    if (synOrder.getSendWeixin() == 0 || synOrder.getSendWeixin() == 1) {
                        TradeQueue tq = pool.getTradeQueue("Weixin");
                        if (!tq.isExist(synOrder.getOrderNumber())) {
                            tq.add(synOrder);
                        }
                    }

                } else {

                    if (synOrder.getSendAlipay() == 0 || synOrder.getSendAlipay() == 1) {
                        TradeQueue tq = pool.getTradeQueue("AlipayHg");
                        if (!tq.isExist(synOrder.getOrderNumber())) {
                            tq.add(synOrder);
                        }
                    }
                    if (synOrder.getSendAlipayGj() == 0 || synOrder.getSendAlipayGj() == 1) {
                        TradeQueue tq = pool.getTradeQueue("AlipayGj");
                        if (!tq.isExist(synOrder.getOrderNumber())) {
                            tq.add(synOrder);
                        }
                    }
                }

			/*	if ((synOrder.getSendAlipay() == 2 && synOrder.getSendAlipayGj() == 2)
                        || synOrder.getSendWeixin() == 2) {
					if (synOrder.getSendZz() == 0 || synOrder.getSendZz() == 1) {
						TradeQueue tq = pool.getTradeQueue("ZZ");
						if (!tq.isExist(synOrder.getOrderNumber())) {
							tq.add(synOrder);
						}
					}
				}*/
            }

        }

    }

    //	@Scheduled(cron = "${gj.job.cron}")
    public void gjReceiveResponseJob() {
        log.info("开始接收国检海关回执-----");
        kllMainOrderService.receiveGjXmlResponse();
        kllMainOrderService.receiveHgXmlResponse();
        log.info("结束接收国检海关回执-----");
    }

    /**
     * 轮询宁波仓推送成功的订单状态
     *
     * @throws Exception
     */
    @Scheduled(cron = "${edi.order.status}")
    public void EDIResponseJob() throws Exception {
        String wareType = env.getProperty("kll.warehouse.nb");
        // 查询订单新增成功的数据
        List<KllOrderSynApi> ediList = kllOrderSynApiRepository.findEDISynApiList(wareType);
        // 遍历
        for (KllOrderSynApi api : ediList) {

            receiveStatus(api);
        }
    }

    public void receiveStatus(KllOrderSynApi api) throws Exception {

        String ranNumber = RandomNumber.getRandom();
        String date = DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSS");
        String msgId = date + ranNumber;
        String data = assmbleyEDIXml(api);
        String url = env.getProperty("edi.order.query");
        String result = postNr(data, url);
//			log.info("EDI:SEL.response=" + result);
        Document document = DocumentHelper.parseText(result);
        Element root = document.getRootElement();// 得到根节点
        String success = ((Element) root.selectSingleNode("//result")).getText();
        String code = ((Element) root.selectSingleNode("//code")).getText();

        if (StringUtils.isNotBlank(success) && success.equals("success")) {
            String orderStatus = ((Element) root.selectSingleNode("//orderProcess//process//orderStatus")).getText();
            log.info("EDI:SEL.response.orderNumber=" + api.getOrderNumber() + "&&orderStatus=" + orderStatus);
            if (StringUtils.isNotBlank(orderStatus)) {
                if (orderStatus.equals("订单完成")) {

                    String logisticsCode = ((Element) root.selectSingleNode("//orderProcess//process//logisticsCode"))
                            .getText();

                    // 回写物流单号
						/*String type = env.getProperty("edi.logistics.ningbo");
						if (StringUtils.isNotBlank(logisticsCode)
								&& logisticsCode.equals(env.getProperty("edi.logistics.chang"))) {
							type = env.getProperty("edi.logistics.tiantian");

						} else {
							type = env.getProperty("edi.logistics.yunda");
						}*/
                    //更新达人收货状态
                    kllKolOrderService.updateKolOrder(api.getOrderNumber());

                    // 更新推送池状态
                    kllOrderSynApiRepository.updateSynStatus(api.getOrderNumber(), "EDI_WARE");

                    // 物流写入 清关完成，等待保税仓发货
                    kllOrderLogisticsService.updateAbroad("清关完成，等待保税仓发货", api.getOrderNumber());

                } else if (orderStatus.equals("推送失败")) {
                    // 更新推送池状态
                    kllOrderSynApiRepository.updateSynStatus(api.getOrderNumber(), "EDI_ERROR");
                } else if (orderStatus.equals("订单关闭")){
                    // 更新推送池状态
                    kllOrderSynApiRepository.updateSynStatus(api.getOrderNumber(), "EDI_END");

                }

            }
            Element waybill = ((Element) root.selectSingleNode("//orderProcess//process//waybillNo"));
            String waybillNo = "";
            if (waybill != null) {
                waybillNo = waybill.getText();
            }
            if (StringUtils.isNotBlank(waybillNo)) {
                String type = env.getProperty("edi.logistics.zhongtong");
                kllMainOrderDetailService.updateEDILogistics(api.getOrderNumber(), waybillNo, "", document.asXML(),
                        type);
                //更新EDB库存
//					kllMainOrderService.updateEDBstock(api.getIbillingNumber());
                kllMainOrderDetailService.updateEDILogistics(api.getOrderNumber());
            }
            kllMainOrderService.createResponseLog(api.getOrderNumber(), result, url.toString(), "EDI_SEL",
                    "EDI_SEL", "EDI" + msgId, true);
        } else {
            code = ((Element) root.selectSingleNode("//code")).getText();
            kllMainOrderService.createResponseLog(api.getOrderNumber(), result, url.toString(), "EDI_SEL",
                    "EDI_ERROR", "EDI" + msgId, false);
        }
    }


    public String postNr(String data, String url) throws Exception {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datetime = sf.format(new Date());
        String secretKey = env.getProperty("edi.secret.key");
        // 签名 base64(md5(报文+密钥+时间))转大写
        String signs = MD5Utils.MD5AndBase64(data + secretKey + datetime).toUpperCase();
        Map<String, String> params = new HashMap<String, String>();
        params.put("data", URLEncoder.encode(data, "UTF-8"));
        params.put("customer", env.getProperty("edi.bus.code"));
        params.put("appkey", env.getProperty("edi.appkey"));
        params.put("secretKey", secretKey);
        params.put("datetime", datetime);
        params.put("sign", URLEncoder.encode(signs, "UTF-8"));
        params.put("serialno", new Date().getTime() + RandomNumber.getRandom());

        String result = HttpUtils.sendPost(url, params);
        return result;
    }

    /**
     * 海关回执预警措施
     */
//	@Scheduled(cron = "${nsapi.send.exmail}")
    public void checkHGresult() {

        List<KllOrderSynApi> synList = kllOrderSynApiRepository.findSynApiHGList();
        for (KllOrderSynApi api : synList) {
            // 两个小时没有回执的重推推送
            Date time = api.getSendHgDate();
            Date hours = DateUtil.beforeTwoHourToNowDate();
            if (hours.after(time)) {
                // 该海关订单重推
                kllOrderSynApiRepository.updateHGRestart(api.getOrderNumber());
            }
        }
    }


    /**
     * nr重推
     */
//	@Scheduled(cron = "${nsapi.send.exmail}")
    public void checkNrresult() {

        List<KllOrderSynApi> synList = kllOrderSynApiRepository.findSynApiNrList();
        for (KllOrderSynApi api : synList) {
            SimpleDateFormat sFormat = new SimpleDateFormat("YYYYMMddHHmmss");
            String msgId = sFormat.format(new Date()) + RandomNumber.getRandom();
            kllMainOrderService.sendXml(api.getOrderNumber(), "EDI", msgId);
        }
    }

    /**
     * 南沙问题订单发送邮件
     */
//	@Scheduled(cron = "${nsapi.send.exmail}")
    public void sendExmail() {
        Date date = DateUtil.beforeOneDayToNowDate();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = df.format(date);
        String endDate = df.format(new Date());
        List<KllOrderSynApi> synList = kllOrderSynApiRepository.findSynApiListExmail(startDate, endDate);
        StringBuffer order = new StringBuffer();
        StringBuffer alipay = new StringBuffer();
        StringBuffer weixin = new StringBuffer();
        StringBuffer zz = new StringBuffer();
        StringBuffer nr = new StringBuffer();
        String content = "";
        order.append("一.国检海关有问题订单列表:\r\n");
        alipay.append("二.国检海关支付单有问题订单列表:\r\n");
        weixin.append("三.微信支付单有问题订单列表:\r\n");
        zz.append("四.卓志有问题订单列表:\r\n");
        nr.append("五.能容有问题订单列表:\r\n");
        for (int i = 0; i < synList.size(); i++) {
            KllOrderSynApi syn = synList.get(i);

            if (syn != null) {
                // 物流写入 订单提交成功，等待海关清关
                // kllOrderLogisticsService.updateAbroad("清关失败",
                // syn.getOrderNumber());

                List<KllMq> list = kllMqService.findByOrderNumber(syn.getOrderNumber());
                Integer gj = syn.getSendGj();
                Integer hg = syn.getSendHg();
                Integer alipayHg = syn.getSendAlipay();
                Integer alipayGj = syn.getSendAlipayGj();
                Integer wei = syn.getSendWeixin();
                Integer sendzz = syn.getSendZz();
                Integer sendnr = syn.getSendNr();
                String info = "";
                if (gj == 3 || hg == 3) {
                    order.append("订单号:" + syn.getOrderNumber() + ",ibilling号:" + syn.getIbillingNumber() + "\r\n");
                    for (int k = 0; k < list.size(); k++) {
                        KllMq mq = list.get(k);
                        if (mq != null) {
                            String msgChannel = mq.getMsg_channel();
                            int status = mq.getMsg_status();

                            if (StringUtils.isNotBlank(msgChannel) && status == 0) {
                                if (msgChannel.equals("HG")) {
                                    info = Dom4jUitls.readStringXml(mq.getMsg_response(), "HG");
                                    order.append("=>=>=>海关错误信息===:" + info + "\r\n\r\n");
                                }
                                if (msgChannel.equals("GJ")) {
                                    info = Dom4jUitls.readStringXml(mq.getMsg_response(), "GJ");
                                    order.append("=>=>=>国检错误信息===:" + info + "\r\n\r\n");
                                }
                            }
                        }
                    }

                }
                if (alipayHg == 3 || alipayGj == 3) {
                    alipay.append("订单号:" + syn.getOrderNumber() + ",ibilling号:" + syn.getIbillingNumber() + "\r\n\r\n");
                }

                if (wei == 3) {
                    weixin.append("订单号:" + syn.getOrderNumber() + ",ibilling号:" + syn.getIbillingNumber() + "\r\n\r\n");
                }
                if (sendzz == 3) {
                    zz.append("订单号:" + syn.getOrderNumber() + ",ibilling号:" + syn.getIbillingNumber() + "\r\n\r\n");
                    for (int j = 0; j < list.size(); j++) {
                        KllMq mq = list.get(j);
                        if (mq != null) {
                            String msgChannel = mq.getMsg_channel();
                            int stauts = mq.getMsg_status();
                            if (StringUtils.isNotBlank(msgChannel) && msgChannel.equals("ZZ") && stauts == 0) {
                                zz.append("=>=>=>错误信息===:" + mq.getMsg_response() + "\r\n\r\n");
                            }
                        }
                    }
                }
                if (sendnr == 3) {
                    nr.append("订单号:" + syn.getOrderNumber() + ",ibilling号:" + syn.getIbillingNumber() + "\r\n\r\n");
                    for (int j = 0; j < list.size(); j++) {
                        KllMq mq = list.get(j);
                        if (mq != null) {
                            String msgChannel = mq.getMsg_channel();
                            int stauts = mq.getMsg_status();
                            if (StringUtils.isNotBlank(msgChannel) && msgChannel.equals("EDI") && stauts == 0) {
                                nr.append("=>=>=>错误信息===:" + mq.getMsg_response() + "\r\n\r\n");
                            }
                        }
                    }
                }
            }
        }
        if (synList != null && synList.size() > 0) {
            content = order.toString() + alipay.toString() + weixin.toString() + zz.toString() + nr.toString();
        } else {
            content = order.append("本期订单无异常!\r\n").toString() + alipay.append("本期订单无异常!\r\n").toString()
                    + weixin.append("本期订单无异常!\r\n").toString() + zz.append("本期订单无异常!\r\n");
        }
        try {
            log.info("邮件内容:" + content);
            String emails = env.getProperty("nsapi.mail.receiver");
            sendEmailService.sendExmail(content, emails);
        } catch (Exception e) {
            log.info("邮件异常:" + e.getMessage());
        }

    }

    /**
     * 卓志异常订单操作
     *
     * @param ibillingNumber
     * @param
     */
    public void updateZZStatus(String ibillingNumber) {
        kllOrderSynApiRepository.updateZZStatus(ibillingNumber);
    }

    /**
     * 获取24小时内未发货订单
     *
     * @throws DocumentException
     */
    @Scheduled(cron = "${nr.logistic.exmail}")
    public void sendLogisticExmail() throws DocumentException {
        //获取未发货订单
        List<KllOrderSynApi> list = kllOrderSynApiRepository.getLogisticExmail();
        StringBuffer content = new StringBuffer();
        content.append("一.卡路里24小时内未发货订单\r\n\r\n");
        boolean flag = false;
        for (KllOrderSynApi api : list) {

            List<KllMq> mq = kllMqService.getListByChannel(api.getOrderNumber(), "EDI_SEL");
            if (mq != null && mq.size() > 0) {
                String result = mq.get(0).getMsg_response();

                Document document = DocumentHelper.parseText(result);
                Element root = document.getRootElement();// 得到根节点
                Element waybill = ((Element) root.selectSingleNode("//orderProcess//process//waybillNo"));
                String waybillNo = "";
                if (waybill != null) {
                    waybillNo = waybill.getText();
                }
                if (StringUtils.isNotBlank(waybillNo)) {
                } else {
                    flag = true;
                    content.append("订单号:" + api.getIbillingNumber() + "\r\n");
                    content.append("=>=>=>订单状态信息===:" + result + "\r\n");
                }
            } else {
                flag = true;
                content.append("订单号:" + api.getIbillingNumber() + "\r\n");
                content.append("=>=>=>订单状态信息===: 未获取到订单状态信息,检查订单是否推送正常\r\n");
            }
        }
        if (!flag) {
            content.append("本期订单无异常\r\n");
        }
        if (list != null && list.size() > 0) {

            String emails = env.getProperty("nr.mail.receiver");
            try {
                sendEmailService.sendExmail(content.toString(), emails);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        KllOrderSynApiService api = new KllOrderSynApiService();
        api.sendExmail();
    }

    public void initTradeThread() {
        String[] channels = KllMainOrderService.MSGCHANNEL;
        TradePool pool = TradePool.getTradeInstance();
        for (String channel : channels) {
            TradeContext tradeContext = pool.getTradeContext(channel);
            tradeContext.setKllMainOrderRepository(kllMainOrderRepository);
            tradeContext.setKllMainOrderService(kllMainOrderService);
            tradeContext.setKllOrderSynApiRepository(kllOrderSynApiRepository);
            tradeContext.setKllMainOrderDetailRepository(kllMainOrderDetailRepository);
            tradeContext.setKllMainOrderDetailService(kllMainOrderDetailService);
            tradeContext.setKllMqService(kllMqService);
            pool.initTradeThread(channel);
        }
    }
}
